package com.lishangshan.oas_system.controller.task;

import com.lishangshan.oas_system.common.formValid.BindingResultVOUtil;
import com.lishangshan.oas_system.common.formValid.MapToList;
import com.lishangshan.oas_system.common.formValid.ResultEnum;
import com.lishangshan.oas_system.common.formValid.ResultVO;
import com.lishangshan.oas_system.model.dao.roledao.RoleDao;
import com.lishangshan.oas_system.model.dao.system.StatusDao;
import com.lishangshan.oas_system.model.dao.system.TypeDao;
import com.lishangshan.oas_system.model.dao.taskdao.TaskDao;
import com.lishangshan.oas_system.model.dao.taskdao.TaskloggerDao;
import com.lishangshan.oas_system.model.dao.taskdao.TaskuserDao;
import com.lishangshan.oas_system.model.dao.user.DeptDao;
import com.lishangshan.oas_system.model.dao.user.PositionDao;
import com.lishangshan.oas_system.model.dao.user.UserDao;
import com.lishangshan.oas_system.model.entity.system.SystemStatusList;
import com.lishangshan.oas_system.model.entity.task.Tasklist;
import com.lishangshan.oas_system.model.entity.task.Tasklogger;
import com.lishangshan.oas_system.model.entity.task.Taskuser;
import com.lishangshan.oas_system.model.entity.user.Position;
import com.lishangshan.oas_system.model.entity.user.User;
import com.lishangshan.oas_system.service.task.TaskService;
import com.lishangshan.oas_system.utils.ParameterUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

@Controller
@RequestMapping("/")
public class TaskController {
    Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private TaskDao tdao;
    @Autowired
    private StatusDao sdao;
    @Autowired
    private TypeDao tydao;
    @Autowired
    private UserDao udao;
    @Autowired
    private DeptDao ddao;
    @Autowired
    private TaskuserDao tudao;
    @Autowired
    private TaskService tservice;
    @Autowired
    private TaskloggerDao tldao;
    @Autowired
    private PositionDao pdao;
    @Autowired
    private RoleDao rdao;

    private int size = ParameterUtil.PAGE_SIZE_MIN;

    /**
     * 任务管理面板
     *
     * @return
     */
    @RequestMapping("taskmanage")
    public String index(Model model,
                        @SessionAttribute("userId") Long userId,
                        @RequestParam(value = "page", defaultValue = "0") int page) {

        // 通过发布人id找用户
        User tu = udao.findOne(userId);
        // 根据发布人id查询任务
        Page<Tasklist> tasklist = tservice.index(page, size, null, tu);
        List<Map<String, Object>> list = tservice.index2(tasklist, tu);

        model.addAttribute("tasklist", list);
        model.addAttribute("page", tasklist);
        model.addAttribute("url", "paixu");
        return "task/taskmanage";
    }

    /**
     * 分頁搜索
     *
     * @param model
     * @param userId
     * @param page
     * @param val
     * @param req
     * @return
     */
    //    paixu
    @RequestMapping("paixu")
    public String indexPaging(Model model, @SessionAttribute("userId") Long userId, @RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page
            , @RequestParam(value = "val", required = false) String val, HttpServletRequest req) {
        // 通过发布人id找用户
        User tu = udao.findOne(userId);
        Page<Tasklist> tasklist = null;
        List<Map<String, Object>> list = null;
        if (val == null) {
            val = "";
        }
        // 获取 搜索框 中的值看看是否有值
//        if (!Objects.isNull(val)) { // 如果 val 不为空，则它是搜索框查找
        tasklist = tservice.index(page, size, val, tu);
        list = tservice.index2(tasklist, tu);
//        }
        model.addAttribute("tasklist", list);
        model.addAttribute("page", tasklist);
        model.addAttribute("url", "paixu");
        model.addAttribute("sort", "&val=" + val);
        return "task/managetable";
    }

    /**
     * 新增任务
     */
    @RequestMapping("addtask")
    public ModelAndView index2(@SessionAttribute("userId") Long userId,
                               @RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page, Model model) {
        Pageable pa = new PageRequest(page, size);
        ModelAndView mav = new ModelAndView("task/addtask");
        // 查询部门下面的员工
        Page<User> pagelist = udao.findByFatherId(userId, pa);
        List<User> emplist = pagelist.getContent();
        tservice.someInfo(model);
        // 查职位表
        Iterable<Position> poslist = pdao.findAll();
        mav.addObject("emplist", emplist);
        mav.addObject("poslist", poslist);
        mav.addObject("page", pagelist);
        mav.addObject("url", "names");
        mav.addObject("qufen", "任务");
        return mav;
    }

    /**
     * 新增任务校验
     */
    @RequestMapping("ck_addtask")
    public String addtask(HttpServletRequest request, @Valid Tasklist tlist, BindingResult br, HttpSession session,
                          @RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page, Model model) {
        request.setAttribute("tasklist", tlist);
        Pageable pa = new PageRequest(page, size);

        // 这里返回ResultVO对象，如果校验通过，ResultEnum.SUCCESS.getCode()返回的值为200；否则就是没有通过；
        ResultVO res = BindingResultVOUtil.hasErrors(br);
        System.out.println("tlist:" + tlist);
        if (!ResultEnum.SUCCESS.getCode().equals(res.getCode())) {
            List<Object> list = new MapToList<>().mapToList(res.getData());
            request.setAttribute("errormess", list.get(0).toString());
            System.out.println("list错误的实体类信息：" + tlist);
            System.out.println("list错误详情:" + list);
            System.out.println("list错误第一条:" + list.get(0));
            System.out.println("啊啊啊错误的信息——：" + list.get(0).toString());
            // 下面的info信息是打印出详细的信息
            log.info("getData:{}", res.getData());
            log.info("getCode:{}", res.getCode());
            log.info("getMsg:{}", res.getMsg());

            String userId = ((String) session.getAttribute("userId")).trim();
            Long userid = Long.parseLong(userId);
            tservice.someInfo(model);
            // 查询部门下面的员工
            Page<User> pagelist = udao.findByFatherId(userid, pa);
            List<User> emplist = pagelist.getContent();
            request.setAttribute("emplist", emplist);
            request.setAttribute("page", pagelist);
            return "task/addtask";
        } else {
            return "forward:/addtasks";
        }
    }

    /**
     * 新增任务保存
     */
    @RequestMapping("addtasks")
    public String addtask(@SessionAttribute("userId") Long userId, HttpServletRequest request) {
        User userlist = udao.findOne(userId);
        Tasklist list = (Tasklist) request.getAttribute("tasklist");
        request.getAttribute("success");
        list.setUsersId(userlist);
        list.setPublishTime(new Date());
        list.setModifyTime(new Date());
        tdao.save(list);
        // 分割任务接收人
        StringTokenizer st = new StringTokenizer(list.getReciverlist(), ";");
        while (st.hasMoreElements()) {
            User reciver = udao.findid(st.nextToken());
            Taskuser task = new Taskuser();
            task.setTaskId(list);
            task.setUserId(reciver);
            task.setStatusId(list.getStatusId());
            // 存任务中间表
            tudao.save(task);

        }

        return "redirect:/taskmanage";
    }

    /**
     * 修改任务
     */
    @RequestMapping("edittasks")
    public ModelAndView index3(HttpServletRequest req, @SessionAttribute("userId") Long userId,
                               @RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page, Model model) {
        Pageable pa = new PageRequest(page, size);
        ModelAndView mav = new ModelAndView("task/edittask");
        String taskid = req.getParameter("id");
        tservice.index3(taskid, model, userId, pa, mav);
        return mav;
    }

    /**
     * 修改任务确定
     */
    @RequestMapping("update")
    public String update(Tasklist task, HttpSession session) {
        Long userid = (Long) session.getAttribute("userId");
        User userlist = udao.findOne(userid);
        task.setUsersId(userlist);
        task.setPublishTime(new Date());
        task.setModifyTime(new Date());
        tservice.save(task);

        // 分割任务接收人 还要查找联系人的主键
        StringTokenizer st = new StringTokenizer(task.getReciverlist(), ";");
        while (st.hasMoreElements()) {
            User reciver = udao.findid(st.nextToken());
            Long pkid = udao.findpkId(task.getTaskId(), reciver.getUserId());
            Taskuser tasku = new Taskuser();
            tasku.setPkId(pkid);
            tasku.setTaskId(task);
            tasku.setUserId(reciver);
            tasku.setStatusId(task.getStatusId());
            // 存任务中间表
            tudao.save(tasku);

        }

        return "redirect:/taskmanage";

    }

    /**
     * 查看任务
     */
    @RequestMapping("seetasks")
    public ModelAndView index4(HttpServletRequest req, Model model) {
//        req.getSession().removeAttribute("page");
        ModelAndView mav = null;
        if (req.getParameter("taskflag") != null) {
            if ("mytask".equals(req.getParameter("taskflag"))) {
                mav = new ModelAndView("task/myseetask");
            } else {
                mav = new ModelAndView("task/seetask");
            }
        }
        // 得到任务的 id
        String taskid = req.getParameter("id");
        Long ltaskid = Long.parseLong(taskid);
        // 通过任务id得到相应的任务
        Tasklist task = tdao.findOne(ltaskid);
        Long statusid = task.getStatusId().longValue();

        // 根据状态id查看状态表
        SystemStatusList status = sdao.findOne(statusid);
        // 查看发布人
        User user = udao.findOne(task.getUsersId().getUserId());
        // 查看任务日志表
        List<Tasklogger> logger = tldao.findByTaskId(ltaskid);
        tservice.someInfo(model);
        mav.addObject("task", task);
        mav.addObject("user", user);
        mav.addObject("status", status);
        mav.addObject("loggerlist", logger);
        mav.addObject("page", req.getParameter("page"));
        return mav;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping("shanchu")
    public String delete(@RequestParam("id") Long id, Model model, HttpServletRequest req) {
        // 查找 task_user表是否存在数据
        List<Taskuser> taskusers = tudao.findAllByTakeId(id);
        if (taskusers.size() > 0) { // 如果 task_user表存在 则先删除task_user表数据
            taskusers.forEach(tu -> {
                tudao.delete(tu.getPkId());
            });
        }
        // 删除 反馈表 相关数据
        List<Tasklogger> taskloggers = tldao.findByTaskId(id);
        if (taskloggers.size() > 0) { // 如果 task_user表存在 则先删除task_user表数据
            taskloggers.forEach(tl -> {
                tldao.delete(tl.getLoggerId());
            });
        }
        // 删除完成后在删除 task表中数据
        tdao.delete(id);
        model.addAttribute("success", "删除成功");
        req.getSession().setAttribute("page", Long.parseLong(req.getParameter("page")));
        String taskflag = req.getParameter("taskflag");
        System.out.println("taskflag = " + taskflag);
        if ("mytask".equals(taskflag)) {
            return "forward:/mytask";
        }
        return "forward:/taskmanage";
    }

    /**
     * 查看 改变 状态并添加反馈
     *
     * @param req
     * @param model
     * @return
     */
    @RequestMapping("tasklogger")
    public String tasklogger(HttpServletRequest req, Model model, @SessionAttribute("userId") Long userId) {
        User user = udao.findOne(userId); // 获取当前登录的用户信息

        String loggerStatusid = req.getParameter("loggerStatusid"); // 状态
        String loggerTicking = req.getParameter("loggerTicking");//反馈
        String taskId = req.getParameter("taskId"); // 获取 当前任务id
        Tasklist tasklist = tdao.findOne(Long.parseLong(taskId));
        tasklist.setStatusId(Integer.parseInt(loggerStatusid));
        tasklist.setTicking(loggerTicking);
        Tasklist tasklist1 = tdao.save(tasklist); // 修改 tasklist表中状态
        // 保存 反馈 列表数据
        Tasklogger tasklogger = new Tasklogger();
        tasklogger.setCreateTime(new Date());// 反馈时间
        tasklogger.setLoggerTicking(loggerTicking);// 反馈内容
        tasklogger.setLoggerStatusid(tasklist1.getStatusId());// 状态id
        tasklogger.setTaskId(tasklist1);// 任务表id
        tasklogger.setUsername(user.getUserName());//  反馈用户名
        tldao.save(tasklogger);
        model.addAttribute("success", "保存成功!");
        req.getSession().setAttribute("page", Long.parseLong(req.getParameter("page")));
        String taskflag = req.getParameter("taskflag");
        System.out.println("taskflag = " + taskflag);
        if ("mytask".equals(taskflag)) {
            return "forward:/mytask";
        }
        return "forward:/taskmanage";
    }

    @RequestMapping("taskTop")
    @ResponseBody
    public String taskTop(@RequestParam("taskId") Long taskId) {
        System.out.println("taskId = " + taskId);
        // 根据 taskId 查询 此条人物信息
        Tasklist tasklist = tdao.findOne(taskId);
        // 如果为true 则是置顶我们将其修改为不置顶
        if (tasklist.getTop() == true) {
            tasklist.setTop(false);
        } else {
            tasklist.setTop(true);
        }
        tdao.save(tasklist);
        return "1";
    }
}
